package de.blitzcoder.cddatabase.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.ListIterator;

/**
 *
 * @author blitzcoder
 */
public class Data {

    private static File SAVEFILE = new File("data.obj");
    public static ArrayList<CD> cdList;


    static {
        loadData();
    }

    /*
    public static void main(String[] args) {
        cdList.add(new CD("Thriller", 1988, "Micheal Jackson"));
        cdList.add(new CD("Earth", 1990, "Micheal Jackson"));
        cdList.add(new CD("Jail", 1977, "Micheal Jackson"));
        cdList.add(new CD("The Eminem Show", 1988, "Eminem"));
        cdList.add(new CD("Dookie", 1988, "Green Day"));
        saveData();
    }*/

    public static void loadData() {

        if (SAVEFILE.exists()) {

            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SAVEFILE));
                cdList = (ArrayList<CD>)ois.readObject();
                ois.close();
            } catch (Exception ex) {
                cdList = new ArrayList<CD>();
            }

        } else {
            cdList = new ArrayList<CD>();
        }

    }

    public static int getDuration() {
        ListIterator<CD> it = cdList.listIterator();
        int count = 0;
        while (it.hasNext()) {
            CD cd = it.next();
            Track[] tracks = cd.getTracks();
            for(Track t:tracks)
                count+=t.getDuration();
        }
            
        return count;
    }

    public static void saveData() {
        SAVEFILE.delete();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVEFILE));
            oos.writeObject(cdList);
            oos.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static int getTrackCount() {
        ListIterator<CD> it = cdList.listIterator();
        int count = 0;
        while (it.hasNext())
            count+=it.next().getTrackList().size();
        return count;
    }

}
